package com.dianrui.operation.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.dianrui.operation.Constant;
import com.dianrui.operation.MyApplication;
import com.dianrui.operation.R;
import com.dianrui.operation.okhttp.XHttpRequest;
import com.dianrui.operation.util.BitmapUtils;
import com.dianrui.operation.util.ConvertUtils;
import com.dianrui.operation.util.GlideUtil;
import com.dianrui.operation.util.MyUtil;
import com.dianrui.operation.util.SharedUtil;
import com.dianrui.operation.util.StringUtils;
import com.dianrui.operation.util.ToastUtil;
import com.dianrui.operation.util.Url;
import com.dianrui.operation.view.ninegride.NineView;
import com.dianrui.operation.view.ninegride.RatioImageView;
import com.dianrui.operation.view.opertionzxing.activity.OpeationCaptureActivity;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;

/**
 * 违章
 */
public class BreakRuleInfoActivity extends BaseActivity implements AMapLocationListener, NineView.NineViewShowCallBack {
    private List<String> imageList = new ArrayList<>();
    private String lat;
    private String lng;
    public AMapLocationClient mLocationClient;
    public AMapLocationClientOption mLocationOption = null;
    private boolean isFirstLoc = true;
    private String carnumber,address;

    @BindView(R.id.car_name_input)
    EditText carNameInput;
    @BindView(R.id.car_name_location)
    EditText carNameLocation;
    @BindView(R.id.money)
    EditText money;
    @BindView(R.id.break_car_type)
    EditText breakCarType;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.nine)
    NineView nine;
    @BindView(R.id.input)
    EditText input;
    @BindView(R.id.sub_feedback)
    Button subFeedback;
    private String violation_id;


    @Override
    public int getContentViewId() {
        return R.layout.activity_breakrule_info;
    }

    @Override
    public void initView() {
        if (getIntent() != null && getIntent().getExtras()!=null) {
            Bundle bundle=getIntent().getExtras();
            carnumber=bundle.getString("carnumber");
            address=bundle.getString("address");
        }
        title.setText(getString(R.string.break_rule_txt));
        imageList.add("default");
        carNameInput.setText(carnumber);
        carNameLocation.setText(address);
        nine.maxCount(9).CloseSize(70).isShowCloseButton(true).spacing(3).setNineViewShowCallBack(this).setUrlList(imageList);

        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(BreakRuleInfoActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                startLocation();
            } else {
                ActivityCompat.requestPermissions(BreakRuleInfoActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
            }
        } else {
            startLocation();
        }
        input.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length()>0) {
                    subFeedback.setBackgroundResource(R.drawable.red_shape1);
                }else {
                    subFeedback.setBackgroundResource(R.drawable.gray_shape);
                }

            }
        });
        getViolationShow();
    }

    private void getViolationShow() {
        JsonObject jsonObject=new JsonObject();
        jsonObject.addProperty("violation_id",violation_id);
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.VIOLATIONSHOW, jsonObject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject != null &&!isFinishing()) {

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {

            }
        });
    }


    @Override
    public void initData() {}


    //开始定位
    private void startLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为Hight_Accuracy高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();

    }

    @Override
    public void onDisplayOneImage(RatioImageView imageView, String url, int parentWidth, Context context) {
        if ("default".equals(url)) {
            addImageViewList(GlideUtil.glideLoad(false, imageView, BreakRuleInfoActivity.this, R.mipmap.add_photo));
        } else {
            imageView.setTag(R.id.glide_tag, url);
            addImageViewList(GlideUtil.downLoader(false, imageView, BreakRuleInfoActivity.this));
        }
    }

    @Override
    public void onDisplayImage(RatioImageView imageView, RatioImageView closeButton, String url, int parentWidth, Context context) {
        if ("default".equals(url)) {
            addImageViewList(GlideUtil.glideLoad(false, imageView, BreakRuleInfoActivity.this, R.mipmap.add_photo));
            if (closeButton != null) {
                closeButton.setVisibility(View.GONE);
            }
        } else {
            imageView.setTag(R.id.glide_tag, url);
            addImageViewList(GlideUtil.downLoader(false, imageView, BreakRuleInfoActivity.this));
            if (closeButton != null) {
                closeButton.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onClickImage(int position, String url, List<String> urlList, Context context) {
        if ("default".equals(url)) {
            int count = 9;
            if (imageList.size() > 1) {
                count = 9 - imageList.size() + 1;
            }
            MyUtil.createPhotoChooseDialog(0, count, BreakRuleInfoActivity.this, MyApplication.getFunctionConfig(), new GalleryFinal.OnHanlderResultCallback() {
                @Override
                public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                    if (resultList == null || resultList.size() == 0) {
                        return;
                    }

                    for (int i = 0; i < imageList.size(); i++) {
                        if ("default".equals(imageList.get(i))) {
                            imageList.remove(i);
                        }
                    }
                    for (int i = 0; i < resultList.size(); i++) {
                        imageList.add(resultList.get(i).getPhotoPath());
                    }
                    if (imageList.size() < 9) {
                        imageList.add("default");
                    }
                    nine.urlList(imageList);

                }

                @Override
                public void onHanlderFailure(int requestCode, String errorMsg) {
                }
            });
        }
    }

    @Override
    public void onClickImageColse(int position, String url, List<String> urlList, Context context) {
        imageList.remove(position);
        int count = 0;
        for (int i = 0; i < imageList.size(); i++) {
            if ("default".equals(imageList.get(i))) {
                count++;
            }
        }
        if (count == 0) {
            imageList.add("default");
        }

        nine.urlList(imageList);
    }

    @Override
    public void onSamePhotos(List<String> mRejectUrlList) {

    }

    @OnClick({R.id.back, R.id.sub_feedback, R.id.scans})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.sub_feedback:
                    if (StringUtils.isEmpty(carNameInput.getText().toString().trim())) {
                        ToastUtil.showToast(getString(R.string.input_car_number_error));
                        return;
                    }
                    if (carNameInput.getText().toString().length()<8) {
                        ToastUtil.showToast(getString(R.string.input_car_number_incorrect));
                        return;
                    }

                    if (StringUtils.isEmpty(carNameLocation.getText().toString().trim())) {
                        ToastUtil.showToast("请输入违章位置");
                        return;
                    }
                    if (StringUtils.isEmpty(money.getText().toString().trim())) {
                        ToastUtil.showToast("请输入罚款金额");
                        return;
                    }
                    if (StringUtils.isEmpty(breakCarType.getText().toString().trim())) {
                        ToastUtil.showToast("请输入违章类型");
                        return;
                    }

                    if (StringUtils.isEmpty(input.getText().toString().trim())) {
                        ToastUtil.showToast("请输入违章描述");
                        return;
                    }
                    report();

                break;

            case R.id.scans:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(BreakRuleInfoActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                        Intent intent = new Intent(BreakRuleInfoActivity.this, OpeationCaptureActivity.class);
                        intent.putExtra("camflag", "1");
                        startActivityForResult(intent, 102);
                    } else {
                        ActivityCompat.requestPermissions(BreakRuleInfoActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                    }
                } else {
                    Intent intent = new Intent(BreakRuleInfoActivity.this, OpeationCaptureActivity.class);
                    intent.putExtra("camflag", "1");
                    startActivityForResult(intent, 102);
                }
                break;

                default:
                    break;
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 102) {
            String imel = data.getStringExtra("IMEI");
            if (!StringUtils.isEmpty(imel)) {
                carNameInput.setText(imel);
            }

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent(BreakRuleInfoActivity.this, OpeationCaptureActivity.class);
                    intent.putExtra("camflag", "1");
                    startActivityForResult(intent, 102);
                }
                break;

            default:
                break;
        }

    }

    private void report() {
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < imageList.size(); i++) {
            if (!"default".equals(imageList.get(i))) {
                jsonArray.put(ConvertUtils.bitmapToBase64(BitmapUtils.decodeSampledBitmapFromFile(imageList.get(i), 480, 960)));
            }

        }

        showLoadingDialog(getString(R.string.upload_error));
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("vehicle_number", carNameInput.getText().toString().trim());
            jsonObject.put("address", carNameLocation.getText().toString().trim());
            jsonObject.put("title", breakCarType.getText().toString().trim());
            jsonObject.put("money", money.getText().toString().trim());
            jsonObject.put("remark", input.getText().toString().trim());
            jsonObject.put("picture", jsonArray);
            jsonObject.put("lng", lng);
            jsonObject.put("lat", lat);
            XHttpRequest.getInstance().postRequests(SharedUtil.getUrl()+Url.VIOTAIONSFEEDBACKS, jsonObject.toString(), new XHttpRequest.XCallBack() {
                @Override
                public void onResponse(String response) {
                    if (!StringUtils.isEmpty(response)) {
                        try {
                            final JSONObject jsonObject = new JSONObject(response);
                            if (null!=jsonObject && !isFinishing()) {
                                if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                    dismissLoadingDialog();
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                    finish();
                                } else if ("1001".equals(jsonObject.optString("status"))) {
                                    dismissLoadingDialog();
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                } else if ("1002".equals(jsonObject.optString("status"))) {
                                    dismissLoadingDialog();
                                    spUtils.clear();
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                    SharedUtil.setToken("");
                                    JumpActivitys(LoginActivity.class);
                                    finish();
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void failedRequest(String result) {
                    dismissLoadingDialog();
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
            if (isFirstLoc) {
                lat=aMapLocation.getLatitude()+"";
                lng=aMapLocation.getLongitude()+"";
                isFirstLoc = false;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
    }
}
